package com.du.javaweb.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author : DuJiabao
 * @Date : 2021/3/28 17:08
 * @Project : java-web
 * @File : ${FILE_NAME}
 * @Desc :
 */

@WebServlet(name = "AddValueSessionServlet", value = "/AddValueSessionServlet")
public class AddValueSessionServlet extends HttpServlet {
  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType("text/html; charset=UTF-8");
    PrintWriter writer = response.getWriter();


    //Cookie jSessionIdCookie = CookieUtils.findCookie("JSESSIONID", request.getCookies());
    //if (jSessionIdCookie != null) {
    //  jSessionIdCookie.setMaxAge(60 * 60 * 24);  // 保存一天
    //  response.addCookie(jSessionIdCookie);
    //}

    // 获取该客户端的session，如果没有，就会创建一个ID，并放入Cookie中，发送给客户端
    HttpSession session = request.getSession();
    if (session.isNew()) {
      writer.write("当前是新的Session <br/>");
    } else {
      writer.write("当前是旧的Session <br/>");
    }
    writer.write("当前SESSION ID为 " + session.getId() + " <br/> ");

    session.setAttribute("key", "value");
    // 设置Session距离上一次请求的生命长度
    session.setMaxInactiveInterval(3);
    writer.write("已经存了数据 <br/>");
  }

  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    doGet(request, response);
  }
}
